<template lang="pug">
  v-dialog(v-model="active" persistent max-width="600px")
    v-card
      v-card-title 添加修改记录
      v-card-text
        v-container
          v-form(ref="form")
            v-select(
              :rules="[rules.required]"
              :items="assetStockChangeHistoryActions"
              label="类型"
              v-model="changeHistory.action_id"
              item-text="name"
              item-value="id")
            v-text-field(
              label="数量"
              type="number"
              v-model="changeHistory.quantity"
            )
            v-textarea(label="描述" v-model="changeHistory.comment")
      v-card-actions
        v-spacer
        v-btn( text @click="active = false") 取消
        v-btn( text @click="add" color="primary") 确认
</template>

<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import {AssetStockChangeHistory} from '@/store/modules/types/AssetStock'
  import {mapActions, mapState} from 'vuex'

  export default (Vue as VueConstructor<Vue & {
    $refs: {},
    getEmptyChangeHistory: () => AssetStockChangeHistory
  }>).extend({
    props: ['asset'],
    methods: {
      ...mapActions("assetStock", {store: "addChangeHistory"}),
      add() {
        if (this.$refs.form.validate()) {
          this.$loading('保存中...')
          let postData = [this.asset.id, this.changeHistory]
          this.store(postData).then((response:any)=>{
            if (!response.data.error) {
              this.$emit("addSuccess")
              this.active = false
            }else {
              this.$msgBox("保存失败 " + response.data.message)
            }

          }).finally(()=>{
            this.$loading.close()
          })
        }
      },
      getEmptyChangeHistory(): AssetStockChangeHistory {
        return {
          id: null,
          action_id: null,
          asset_stock_id: null,
          comment: null,
          quantity: 0,
          user_id: null
        }
      },
      reset(){
        this.changeHistory = Object.assign({}, this.getEmptyChangeHistory())
      },
      toggle() {
        this.reset()
        this.active = !this.active
      }
    },
    computed: {
      ...mapState('asset', ['assetStockChangeHistoryActions'])
    },
    data() {
      let changeHistory: AssetStockChangeHistory = this.getEmptyChangeHistory()
      return {
        changeHistory: changeHistory,
        active: false,
        rules: {
          required: (value: any) => !!value || '必填'
        },
      }
    }
  })
</script>
